import socket
import time
import random
import threading
from datetime import datetime

class BrainSignalSender:
    def __init__(self, host='127.0.0.1', port=8888):
        self.host = host
        self.port = port
        self.socket = None
        self.running = False
        
    def connect_to_server(self):
        """连接到服务器"""
        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.connect((self.host, self.port))
            print(f"已连接到服务器 {self.host}:{self.port}")
            return True
        except Exception as e:
            print(f"连接失败: {e}")
            return False
    
    def start_sending(self):
        """开始发送模拟数据"""
        if not self.socket:
            print("未连接到服务器")
            return
            
        print("开始发送模拟脑机信号数据...")
        print("数据格式: 方向信号(上/下/左/右)，每100ms发送一次")
        
        self.running = True
        
        while self.running:
            try:
                signal = self.generate_signal()
                timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3]
                data = f"{signal}\n"  # 以换行符结束每条数据
                
                self.socket.sendall(data.encode('utf-8'))
                print(f"[{timestamp}] 发送: {signal}")
                
                # 等待100ms
                time.sleep(0.1)
                
            except Exception as e:
                print(f"发送数据时发生错误: {e}")
                self.running = False
    
    def generate_signal(self):
        """生成模拟的脑机信号"""
        # 随机生成方向信号
        directions = ['上', '下', '左', '右']
        
        # 80%的概率生成连续相同的信号，20%的概率生成随机信号
        if random.random() < 0.8 and hasattr(self, 'last_signal'):
            signal = self.last_signal
        else:
            signal = random.choice(directions)
            self.last_signal = signal
            
        return signal
    
    def send_custom_sequence(self, sequence):
        """发送自定义的信号序列"""
        if not self.socket:
            print("未连接到服务器")
            return
            
        print(f"发送自定义序列: {sequence}")
        for signal in sequence:
            if not self.running:
                break
                
            data = f"{signal}\n"
            timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3]
            
            try:
                self.socket.sendall(data.encode('utf-8'))
                print(f"[{timestamp}] 发送: {signal}")
            except Exception as e:
                print(f"发送数据时发生错误: {e}")
                break
            
            time.sleep(0.1)
    
    def stop_sending(self):
        """停止发送"""
        self.running = False
        if self.socket:
            self.socket.close()
        print("发送已停止")

def interactive_mode(sender):
    """交互模式，允许用户手动输入信号"""
    print("\n交互模式已启动")
    print("输入方向(上/下/左/右)并按回车发送，输入'quit'退出交互模式")
    
    while sender.running:
        try:
            user_input = input("> ").strip()
            if user_input.lower() == 'quit':
                break
            elif user_input in ['上', '下', '左', '右']:
                data = f"{user_input}\n"
                timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3]
                
                try:
                    sender.socket.sendall(data.encode('utf-8'))
                    print(f"[{timestamp}] 发送: {user_input}")
                except Exception as e:
                    print(f"发送失败: {e}")
                    break
            else:
                print("无效输入，请输入: 上, 下, 左, 右 或 quit")
        except KeyboardInterrupt:
            break
        except Exception as e:
            print(f"交互模式错误: {e}")

if __name__ == "__main__":
    sender = BrainSignalSender()
    
    print("=" * 50)
    if sender.connect_to_server():
        print("\n选择发送模式:")
        print("1. 自动模式 (随机生成信号)")
        print("2. 交互模式 (手动输入信号)")
        print("3. 预设序列模式")
        
        mode_choice = input("请选择模式 (1/2/3): ").strip()
        
        if mode_choice == "1":
            # 自动模式
            try:
                sender.start_sending()
            except KeyboardInterrupt:
                sender.stop_sending()
        elif mode_choice == "2":
            # 交互模式
            interactive_mode(sender)
            sender.stop_sending()
        elif mode_choice == "3":
            # 预设序列模式
            sequence = input("请输入信号序列 (例如: 上上上左左右右右上上上上): ").strip()
            sender.send_custom_sequence(sequence)
            input("序列发送完成，按回车键停止...")
            sender.stop_sending()
        else:
            print("无效选择")
            sender.stop_sending()
    else:
        print("无法连接到服务器")